package com.ys.erp.framework.handler.login;

import com.ys.erp.framework.annotation.CheckEmpLogin;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 校验并注入登录用户
 *
 * @author scy
 * @date 2021/5/9
 */
@Slf4j
public abstract class CheckEmpLoginHandler {

    /**
     * 切入点
     */
    @Pointcut(value = "@within(com.ys.erp.framework.annotation.CheckEmpLogin) ")
    public void permissionTypeCheckCut() {
    }

    @Pointcut(value = "@annotation(com.ys.erp.framework.annotation.CheckEmpLogin)")
    public void permissionMethodCheckCut() {

    }

    /**
     * 检查emp
     *
     * @param request request
     * @param checkUserLogin targetMethod
     */
    public abstract Object checkUserLogin(ProceedingJoinPoint pj, HttpServletRequest request, CheckEmpLogin checkUserLogin) throws Throwable;

    @Around("permissionTypeCheckCut()")
    public Object doBefore(ProceedingJoinPoint pj) throws Throwable {
        Class<?> aClass = pj.getTarget().getClass();
        CheckEmpLogin annotation = aClass.getAnnotation(CheckEmpLogin.class);
        //根据请求头的token获取当前登录用户
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        return checkUserLogin(pj, request, annotation);
    }

    @Around("permissionMethodCheckCut()")
    public Object around(ProceedingJoinPoint pj) throws Throwable {
        Signature signature = pj.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method targetMethod = methodSignature.getMethod();
        CheckEmpLogin annotation = targetMethod.getAnnotation(CheckEmpLogin.class);
        //根据请求头的token获取当前登录用户
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        return checkUserLogin(pj, request, annotation);
    }

}
